<template>
	<basic-container>
		<avue-crud
			:option="option"
			:data="data"
			ref="crud"
			:table-loading="loading"
			:permission="permissionList"
			@row-del="rowDel"
			@row-update="rowUpdate"
			@row-save="rowSave"
			:page="page"
			@refresh-change="refreshChange"
			@current-change="currentChange"
			@size-change="sizeChange"
			@on-load="onLoad"
		>
			<template slot-scope="scope" slot="menu">
				<el-button type="text" size="small" icon="el-icon-edit" @click.stop="handleEdit(scope.row, scope.index)" v-has="'/mall-cloud-base/transArea/editItem'">
					编辑
				</el-button>
				<el-button type="text" size="small" icon="el-icon-edit" @click.stop="handleArea(scope.row, scope.index)" v-has="'/mall-cloud-base/area/bindArea'">
					绑定地区
				</el-button>
			</template>
		</avue-crud>

		<el-dialog title="编辑" :visible.sync="box" width="70%"><avue-form v-model="form" :option="formOption" @submit="editCommit"></avue-form></el-dialog>

		<el-dialog title="绑定省/市" :visible.sync="areaBox" :before-close="handleClose" width="50%">
			<el-tree
				:data="dataTree"
				:props="props"
				show-checkbox
				node-key="value"
				ref="tree"
				:expand-on-click-node="false"
				highlight-current
				:default-checked-keys="treeKeys"
				:load="loadNode"
				@check-change="handleCheckChange"
			></el-tree>

			<div style="margin: 50px auto;">
				<div style="width:200px;margin: 0px auto;">
					<el-button type="primary" size="mini" @click="resetChecked">清空</el-button>
					<el-button type="primary" size="mini" @click="sureData" :loading="bindTree" v-has="'/mall-cloud-base/area/bindArea'">保 存</el-button>
				</div>
			</div>
		</el-dialog>
	</basic-container>
</template>

<script>
import { getList, remove, update, add, getAreaListByLevel } from '@/api/admin/transArea';
import { mapGetters } from 'vuex';
import { testSort, testAreaName } from '@/util/util';
import { getListTree, bindArea, showBack } from '@/api/admin/area';
export default {
	data() {
		return {
			bindTree: false,
			isClickTreeLeftIcon: false, //是否点击了树左边的小图标
			isClickNode: false, //是否是点击了节点
			treeKeys: [],
			dataTree: [],
			props: {
				label: 'label',
				value: 'value',
				children: 'children'
			},
			count: 1,
			/** 二级联动下拉选配置信息start **/
			/** 二级联动配置end **/
			itemList: {},
			query: {},
			loading: true,
			rolesTree: [],
			rolesKeys: [],
			listTree: [],
			provinceAndCityId: [], //要绑定的省市的id
			checked: {}, //最近选择的一次数据
			box: false,
			areaBox: false,
			page: {
				pageSize: 10,
				currentPage: 1,
				total: 0
			},
			option: {
				tip: true, //弹窗编辑文字提示
				addBtn: true, //添加按钮
				menuType: 'text',
				size: 'mini',
				editBtn: false,
				delBtn: true,
				border: true,
				index: true,
				rowKey: 'id',
				height: 'auto',
				menuWidth: 250,
				// calcHeight: 380,
				dialogType: 'dialog',
				align: 'center',
				menuAlign: 'center',
				column: [
					{
						label: '区域名称',
						prop: 'areaName',
						fixed: true,
						rules: [
							{
								required: true,
								message: '请输入区域名称',
								trigger: 'blur'
							},
							{
								validator: testAreaName,
								trigger: 'blur'
							}
						]
					},
					{
						label: '序号',
						prop: 'sequence',
						tip: '越小越靠前',
						rules: [
							{
								required: true,
								message: '请输入序号 越小越靠前',
								trigger: 'blur'
							},
							{
								validator: testSort,
								trigger: 'blur'
							}
						]
					}
				]
			},
			data: [],
			form: {},
			areaForm: {},
			formOption: {
				labelWidth: 150,
				emptyBtn: false,
				column: [
					{
						label: '请输入区域名称',
						prop: 'areaName',
						rules: [
							{
								required: true,
								message: '请输入区域名称',
								trigger: 'blur'
							},
							{
								required: true,
								validator: testAreaName,
								trigger: 'blur'
							}
						]
					},
					{
						label: '序号',
						prop: 'sequence',
						tip: '越小越靠前',
						rules: [
							{
								required: true,
								message: '请输入序号 越小越靠前',
								trigger: 'blur'
							},
							{
								required: true,
								validator: testSort,
								trigger: 'blur'
							}
						]
					}
				]
			},
			areaListByLevel: []
		};
	},
	computed: {
		...mapGetters(['permission', 'userInfo']),
		permissionList() {
			return {
				addBtn: this.vaildData(this.permission['/mall-cloud-base/transArea/addItem'], false),
				viewBtn: this.vaildData(this.permission['/mall-cloud-base/transArea/detail'], false),
				delBtn: this.vaildData(this.permission['/mall-cloud-base/transArea/delete'], false)
			};
		}
	},
	watch: {},
	created() {
		getAreaListByLevel(1).then(res => {
			this.areaListByLevel = res.data.data;
		});
	},
	methods: {
		//表单提交触发事件
		submit(row, loading) {
			loading();
			this.box = false;
		},

		//自定义按钮编辑触发事件
		handleEdit(row, index) {
			this.form.areaName = row.areaName;
			this.form.sequence = row.sequence;
			this.form.id = row.id;
			this.box = true;
		},

		handleArea(row, index) {
			console.log(row);
			this.areaForm.transId = row.id;
			this.areaBox = true;
			//回显数据
			showBack(this.areaForm.transId).then(
				res => {
					if (res.data.success) {
						console.log(res.data);
						if (res.data.data.length != 0) {
							this.treeKeys = res.data.data;
							this.$refs.tree.setCheckedKeys(this.treeKeys);
						} else {
							this.$refs.tree.setCheckedKeys([]);
						}
					} else {
						this.$message.error(res.data.message);
					}
				},
				error => {
					this.$message.error(res.data.message);
				}
			);
		},
		//编辑提交事件
		editCommit(row, loading) {
			update(row).then(
				res => {
					if (res.data.success) {
						loading();
						this.box = false;
						this.onLoad(this.page);
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
					} else {
						this.$message.error(res.data.message);
					}
				},
				error => {
					done();
				}
			);
		},

		rowSave(row, loading, done) {
			row.areaName = row.areaName;
			row.sequence = row.sequence;
			add(row).then(
				res => {
					if (res.data.success) {
						loading();
						this.onLoad(this.page);
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
					} else {
						this.$message.error(res.data.message);
					}
				},
				error => {
					done();
				}
			);
		},
		rowUpdate(row, index, loading, done) {
			row.position = row.positionIds;
			update(row).then(
				res => {
					if (res.data.success) {
						loading();
						this.onLoad(this.page);
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
					} else {
						this.$message.error(res.data.message);
					}
				},
				error => {
					done();
				}
			);
		},
		rowDel(row) {
			this.$confirm('删除区域将会同步删除所有下级区域，是否继续?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					return remove(row.id);
				})
				.then(() => {
					this.onLoad(this.page);
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
				});
		},
		searchReset() {
			this.query = {};
			this.onLoad(this.page);
		},
		searchChange(params) {
			this.query = params;
			this.onLoad(this.page, params);
		},
		currentChange(currentPage) {
			this.page.currentPage = currentPage;
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
		},
		refreshChange() {
			this.onLoad(this.page);
		},
		onLoad(page, params = {}) {
			this.loading = true;
			getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
				this.loading = false;
				const data = res.data;
				this.page.total = data.count;
				this.data = data.data;
				if (data.data.length == 0) {
					//如果当前页没有数据 加载上一页数据
					this.page.currentPage -= 1;
					this.onLoad(this.page);
				}
			});
			getListTree().then(res => {
				//只获取省市
				this.listTree = JSON.parse(JSON.stringify(res.data.data));
				for (let i = 0; i < this.listTree.length; i++) {
					let item = this.listTree[i].children;
					for (let y = 0; y < item.length; y++) {
						delete item[y].children;
					}
				}
				this.dataTree = this.listTree;
			});
		},
		handleCheckChange() {
			let res = this.$refs.tree.getCheckedNodes();
			console.log(res);
			this.provinceAndCityId=[]
			res.forEach(item => {
				this.areaListByLevel.forEach(areas => {
					if (areas.id == item.value) {
						this.provinceAndCityId.push(item.value);
					}
				});
			});
		},
		//加载节点
		loadNode(node, resolve) {
			if (node.level === 0) {
				return resolve(this.listTree);
			}
			if (node.level === 1) {
				for (let i = 0; i < this.listTree.length; i++) {
					if (node.label == this.listTree[i].label) {
						return resolve(this.listTree[i].children);
					}
				}
			}
			if (node.level > 1) return resolve([]);
		},

		//取消
		resetChecked() {
			this.$refs.tree.setCheckedKeys([]);
		},

		// 保存
		sureData() {
			this.bindTree = true;
			console.log(this.provinceAndCityId)
			bindArea(this.provinceAndCityId, this.areaForm.transId).then(
				res => {
					if (res.data.success) {
						this.bindTree = false;
						this.onLoad(this.page);
						this.areaBox = false;
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
						// location.reload()
						this.$nextTick(() => {
							this.onLoad(this.page);
						});
					} else {
						this.bindTree = false;
						this.$message.error(res.data.message);
					}
				},
				error => {
					this.bindTree = false;
				}
			);
		},

		getCheckedNodes() {
			console.log(this.$refs.tree.getCheckedNodes());
		},
		getCheckedKeys() {
			console.log(this.$refs.tree.getCheckedKeys());
		},
		setCheckedNodes() {
			this.$refs.tree.setCheckedNodes([
				{
					id: 5,
					label: '二级 2-1'
				},
				{
					id: 9,
					label: '三级 1-1-1'
				}
			]);
		},
		setCheckedKeys() {
			this.$refs.tree.setCheckedKeys([3]);
		},

		handleClose() {
			this.areaBox = false;
			this.$nextTick(() => {
				this.onLoad(this.page);
			});
		}
	}
};
</script>

<style scoped>
.el-col {
	margin: 0;
}
.el-form-item {
	width: 400px !important;
}
.avue-crud .el-select {
	width: 130px !important;
	padding: 0 5px;
}
.el-button--small {
	padding: 8px 15px;
}
</style>
